<template>
  <!-- 工艺路线模板（新增表）表单弹窗 -->
  <div>
    <el-dialog
      :close-on-click-modal="false"
      v-model="visibleDialog"
      :title="props.title"
      width="900px"
      draggable
      @close="closeDialog"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :inline="true"
        :rules="rules"
        label-width="120"
      >
        <h4 class="mb-[20px] mt-[0px]">基本数据</h4>
        <div>
          <el-row>
            <el-col :span="12">
              <el-form-item label="模板编号" prop="routingTemplateCode">
                <el-input
                  v-if="!props.isReadonly"
                  v-model="formData.routingTemplateCode"
                  placeholder="请输入模板编号"
                  clearable
                />
                <span v-else>{{ formData.routingTemplateCode }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="模板名称" prop="routingTemplateName">
                <el-input
                  v-if="!props.isReadonly"
                  v-model="formData.routingTemplateName"
                  placeholder="请输入模板名称"
                  clearable
                />
                <span v-else>{{ formData.routingTemplateName }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="工厂" prop="plantId">
                <el-select
                  v-if="!props.isReadonly"
                  v-model="formData.plantId"
                  placeholder="请输入工厂"
                  clearable
                  @change="changePlant"
                  filterable
                >
                  <el-option
                    v-for="plant in plantList"
                    :key="plant.id"
                    :label="plant.organizationCode"
                    :value="plant.id"
                  />
                </el-select>
                <span v-else>{{ plantCode(formData.plantId) }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="项目" prop="projectId">
                <el-select
                  v-if="!props.isReadonly"
                  v-model="formData.projectId"
                  placeholder="请输入项目"
                  clearable
                  @change="changeProject"
                  filterable
                >
                  <el-option
                    v-for="project in projectList"
                    :key="project.id"
                    :label="`${project.projectCode}-${project.projectName}`"
                    :value="project.id"
                  />
                </el-select>
                <span v-else>{{ projectCode(formData.projectId) }}</span>
              </el-form-item>
            </el-col>
            <!--<el-col :span="12">
              <el-form-item label="制造环节角色" prop="manufacturingRole">
                <el-select
                  style="width: 100%"
                  v-if="!props.isReadonly"
                  v-model="formData.manufacturingRole"
                  clearable
                  placeholder="请选择制造环节角色"
                >
                  <el-option
                    v-for="item in dictionaryStore.filterDictList(
                      'ManufacturingRole'
                    )"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
                <span v-else>{{
                  dictionaryStore.filterDictName(
                    "ManufacturingRole",
                    formData.manufacturingRole
                  )
                }}</span>
              </el-form-item>
            </el-col>-->
            <el-col :span="12">
              <el-form-item label="是否启用" prop="enabled">
                <el-radio-group
                  v-model="formData.enabled"
                  v-if="!props.isReadonly"
                >
                  <el-radio :label="1">启用</el-radio>
                  <el-radio :label="0">停用</el-radio>
                </el-radio-group>
                <span v-else>{{
                  formData.enabled == 1 ? "启用" : "停用"
                }}</span>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="备注" prop="remarks">
                <el-input
                  v-if="!props.isReadonly"
                  v-model="formData.remarks"
                  style="width: 620px"
                  type="textarea"
                  placeholder="请输入备注"
                  clearable
                />
                <span v-else>{{ formData.remarks }}</span>
              </el-form-item>
            </el-col>
          </el-row>
        </div>
        <h4 class="mb-[20px] mt-[20px]">详细数据</h4>
        <el-card shadow="never" class="table-container">
          <template #header v-if="!props.isReadonly">
            <el-button type="success" plain @click="handleAdd">
              <i-ep-plus />
              新增</el-button
            >
          </template>
          <div class="formTable">
            <el-table
              :data="formData.details"
              style="width: 100%"
              :key="Math.random"
              border
            >
              <el-table-column
                type="index"
                label="序号"
                align="center"
                width="100"
              />
              <el-table-column
                label="顺序号"
                props="workSequence"
                min-width="150"
                align="center"
              >
                <template #default="{ $index, row }">
                  <el-form-item
                    :prop="'details.' + $index + '.workSequence'"
                    :rules="rules.sonworkSequence"
                    label-width="0"
                  >
                    <el-input-number
                      v-if="!props.isReadonly"
                      v-model="row.workSequence"
                      placeholder="请输入顺序号"
                      clearable
                      style="width: 140px"
                      :min="1"
                    />
                    <span v-else>{{ row.workSequence }}</span>
                  </el-form-item>
                </template>
              </el-table-column>
              <!--<el-table-column
                label="工作中心"
                props="workCenterId"
                min-width="150"
              >
                <template #default="{ $index, row }">
                  <el-form-item
                    :prop="'details.' + $index + '.workCenterId'"
                    :rules="rules.sonworkCenterId"
                    label-width="0"
                  >
                    <el-input
                      v-if="!props.isReadonly"
                      v-model="row.workCenterId"
                      placeholder="请输入工作中心"
                      clearable
                    />
                    <span v-else>{{ row.workCenterId }}</span>
                  </el-form-item>
                </template>
              </el-table-column>-->
              <el-table-column
                label="工序"
                props="processId"
                min-width="150"
                align="center"
              >
                <template #default="{ $index, row }">
                  <el-form-item
                    :prop="'details.' + $index + '.processId'"
                    :rules="rules.sonprocessId"
                    label-width="0"
                  >
                    <el-select
                      v-if="!props.isReadonly"
                      v-model="row.processId"
                      placeholder="请输入工序"
                      clearable
                      @change="changeProcess($index, row.processId)"
                      filterable
                    >
                      <el-option
                        v-for="item in processList"
                        :key="item.id"
                        :label="`${item.processCode}-${item.processName}`"
                        :value="item.id"
                      />
                    </el-select>
                    <span v-else>{{ processCode(row.processId) }}</span>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column
                label="是否外协"
                props="isExterior"
                min-width="150"
                align="center"
              >
                <template #default="{ $index, row }">
                  <el-form-item
                    :prop="'details.' + $index + '.isExterior'"
                    :rules="rules.sonisExterior"
                    label-width="0"
                  >
                    <el-radio-group
                      v-model="row.isExterior"
                      v-if="!props.isReadonly"
                    >
                      <el-radio :label="1">是</el-radio>
                      <el-radio :label="0">否</el-radio>
                    </el-radio-group>
                    <span v-else>{{ row.isExterior == 1 ? "是" : "否" }}</span>
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column
                fixed="right"
                align="center"
                label="操作"
                width="100"
                v-if="!props.isReadonly"
              >
                <template #default="scope">
                  <el-button
                    :disabled="formData.details.length < 2"
                    type="danger"
                    link
                    @click.stop="handleDelete(scope.$index)"
                    ><i-ep-delete />
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-card>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button
            v-if="!props.isReadonly"
            type="primary"
            :loading="loading"
            @click="handleSubmit"
            >确 定</el-button
          >
          <el-button @click="closeDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import request from "@/utils/request";
import { useDictStoreHook } from "@/store/modules/dictionary";
import { validateNumber } from "@/utils/commonHooks"; // 引入
const dictionaryStore = useDictStoreHook();

defineOptions({
  name: "MESMESROUTINGTEMPLATEADDORUPDATE",
  inheritAttrs: false,
});

const emit = defineEmits(["reset-table", "change-visible"]);

const props = defineProps({
  visible: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  title: {
    type: String,
    default: () => {
      return "";
    },
  },
  data: {
    type: Object,
    default: () => {
      return {};
    },
  },
  isReadonly: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
});

/** 弹窗显示 **/
const visibleDialog = ref(false);
watch(
  () => props.visible,
  (newVal: boolean) => {
    visibleDialog.value = newVal;
    setTimeout(() => {
      formRef.value.clearValidate();
    }, 50);
  }
);

/** formData定义表单数据 */
const formRef = ref(ElForm);
let formData = reactive({
  id: "",
  routingTemplateCode: "",
  routingTemplateName: "",
  organizationId: "",
  plantId: "",
  plantCode: "",
  projectId: "",
  projectCode: "",
  projectName: "",
  manufacturingRole: "",
  version: "",
  remarks: "",
  createTime: "",
  createdUserId: "",
  createdUserName: "",
  lastUpdateTime: "",
  lastUpdatedUserId: "",
  lastUpdatedUserName: "",
  enabled: 1,
  deleted: "",
  state: "",
  details: [
    {
      id: "",
      workSequence: 1,
      workCenterId: "",
      processId: "",
      processCode: "",
      processName: "",
      routingProcessId: "",
      isExterior: 0,
      version: "",
      remarks: "",
      enabled: "",
      deleted: "",
      createTime: "",
      createdUserId: "",
      createdUserName: "",
      lastUpdateTime: "",
      lastUpdatedUserId: "",
      lastUpdatedUserName: "",
    },
  ],
});

/** rules规则 */
const rules = reactive({
  routingTemplateCode: [
    { required: true, message: "请输入模板编号", trigger: "blur" },
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  routingTemplateName: [
    { required: true, message: "请输入模板名称", trigger: "blur" },
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  plantId: [
    { required: true, message: "请选择工厂", trigger: "change" },
    { min: 1, max: 32, message: "长度在 1 到 32 个字符", trigger: "blur" },
  ],
  projectId: [
    { required: true, message: "请选择项目", trigger: "change" },
    { min: 1, max: 32, message: "长度在 1 到 32 个字符", trigger: "blur" },
  ],
  manufacturingRole: [],
  remarks: [
    { min: 1, max: 255, message: "长度在 1 到 255 个字符", trigger: "blur" },
  ],
  enabled: [],
  sonworkSequence: [
    { required: true, message: "请输入工序顺序", trigger: "blur" },
    {
      validator: (rule, value, callback) =>
        validateNumber(rule, value, callback, formData.details),
      trigger: "blur",
    },
  ],
  sonworkCenterId: [
    { min: 1, max: 32, message: "长度在 1 到 32 个字符", trigger: "blur" },
  ],
  sonprocessId: [
    { required: true, message: "请选择工序", trigger: "change" },
    { min: 1, max: 32, message: "长度在 1 到 32 个字符", trigger: "blur" },
  ],
  sonisExterior: [
    { required: true, message: "请选择是否外协", trigger: "blur" },
  ],
});

const isValidated = ref(false);
/** 删除行 */
const handleDelete = (index: any) => {
  formData.details.splice(index, 1);
  isValidated.value && formRef.value.validate(() => {});
};

const details = {
  id: "",
  workSequence: 1,
  workCenterId: "",
  processId: "",
  routingProcessId: "",
  isExterior: 0,
  version: "",
  remarks: "",
  enabled: "",
  deleted: "",
  createTime: "",
  createdUserId: "",
  createdUserName: "",
  lastUpdateTime: "",
  lastUpdatedUserId: "",
  lastUpdatedUserName: "",
};

/** 添加行 */
const handleAdd = () => {
  let sondata = JSON.parse(JSON.stringify(details));
  formData.details.push(sondata);
};

/** 编辑时赋值 */
watch(
  () => props.data,
  (newVal: any) => {
    formData.id = "";
    if (newVal?.id) {
      Object.assign(formData, props.data);
      if (formData.id) {
        getdetails();
        getProcessList();
        getProjectList();
      }
    }
  }
);

/** 关闭表单弹窗 */
function closeDialog() {
  visibleDialog.value = false;
  emit("change-visible", false);
  resetForm();
}

/** 重置表单 */
function resetForm() {
  formRef.value.resetFields();
  formRef.value.clearValidate();
  formData.details = [JSON.parse(JSON.stringify(details))];
  formData.id = "";
  formData.routingTemplateCode = "";
  formData.routingTemplateName = "";
  formData.organizationId = "";
  formData.plantId = "";
  formData.projectId = "";
  formData.manufacturingRole = "";
  formData.version = "";
  formData.remarks = "";
  formData.createTime = "";
  formData.createdUserId = "";
  formData.createdUserName = "";
  formData.lastUpdateTime = "";
  formData.lastUpdatedUserId = "";
  formData.lastUpdatedUserName = "";
  formData.enabled = 1;
  formData.deleted = "";
  formData.state = "";
  projectList.value = [];
  processList.value = [];
}

const loading = ref(false);

/** 工艺路线模板（新增表）保存提交 */
function handleSubmit() {
  formRef.value.validate(async (valid: any) => {
    if (valid) {
      loading.value = true;
      let text = formData.id ? "编辑" : "新增";
      if (formData.state == 1) {
        text = "复制";
      }
      console.log("formData", toRaw(formData));
      await request({
        url: "/mes/mesroutingtemplate/save",
        method: "post",
        data: formData,
      }).finally(() => {
        loading.value = false;
      });
      ElMessage.success(text + `成功`);
      closeDialog();
      emit("reset-table", formData.id);
      isValidated.value = false;
    } else {
      isValidated.value = true;
    }
  });
}

async function getdetails() {
  let sondetails = await request({
    url: "/mes/mesroutingtemplate/getDetails",
    method: "post",
    data: formData,
  }).finally(() => {
    loading.value = false;
  });
  formData.details = sondetails.data;
}
onMounted(() => {
  getPlantList();
});
//工厂列表
const plantList = ref([]);
const getPlantList = async () => {
  const { data } = await request({
    url: "system/sysOrganization/getList",
    method: "post",
    data: { organizationType: 3 },
  });
  plantList.value = data;
};
const changePlant = (id: any) => {
  formData.plantId = id;
  formData.plantCode = plantCode(id);
  if (id) {
    getProcessList();
    getProjectList();
  } else {
    projectList.value = [];
    formData.projectId = "";
    formData.projectCode = "";
    formData.projectName = "";
    processList.value = [];
    formData.details = [JSON.parse(JSON.stringify(details))];
  }
};
const plantCode = (id: string) => {
  if (id) {
    const data = plantList.value.find((item) => item.id === id);
    return data.organizationCode;
  }
};
//项目列表
const projectList = ref([]);
const getProjectList = async () => {
  const { data } = await request({
    url: "mdm/mdmprojectinfo/getList",
    method: "post",
    data: { enable: 1, plantId: formData.plantId, deleted: 0 },
  });
  projectList.value = data;
};
const changeProject = (id: any) => {
  formData.projectId = id;
  const data = projectList.value.find((item) => item.id === id);
  formData.projectCode = data.projectCode;
  formData.projectName = data.projectName;
};
const projectCode = (id: string) => {
  if (id) {
    const data = projectList.value.find((item) => item.id === id);
    return `${data.projectCode} - ${data.projectName}`;
  }
};
//工序列表
const processList = ref([]);
const getProcessList = async () => {
  const { data } = await request({
    url: "mes/mesprocess/getList",
    method: "post",
    data: { plantId: formData.plantId, enabled: 1 },
  });
  processList.value = data;
};
const changeProcess = (index, id: any) => {
  if (!id) {
    formData.details[index].processId = "";
    formData.details[index].processCode = "";
    formData.details[index].processName = "";
  }
  processList.value.forEach((item: any) => {
    //类型为空是清除信息
    if (item.id == id) {
      formData.details[index].processId = item.id;
      formData.details[index].processCode = item.processCode;
      formData.details[index].processName = item.processName;
      formData.details[index].workCenterId = item.workCenterId;
    }
  });
};
const processCode = (id: string) => {
  if (id) {
    const data = processList.value.find((item) => item.id === id);
    return `${data.processCode} - ${data.processName}`;
  }
};
</script>

<style lang="scss" scoped>
h4 {
  font-weight: 400;
  color: #000;
  padding-left: 10px;
  font-size: 14px;
  line-height: 14px;
}
.formTable {
  :deep(.el-form-item) {
    margin-right: 0 !important;
  }
}
:deep(.el-dialog .el-dialog__body) {
  overflow-y: auto;
  height: 65vh;
}
:deep(.search-container .el-input.el-input--default.el-input--suffix) {
  // 固定宽度
  width: 190px !important;
}
:deep(.search-container .el-form-item--default .el-form-item__label) {
  // 固定宽度
  justify-content: end;
}
</style>
